/*
 * @描述: 我的消息页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { PureComponent, Fragment } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Button, Descriptions, Modal, Icon } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ProTable from '@ant-design/pro-table';

import styles from './MyNotification.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@Form.create()
class ViewForm extends PureComponent {
  static defaultProps = {
    handleView: () => { },
    handleViewModalVisible: () => { },
    values: {}
  };

  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        title: props.values.title,
        publisher: props.values.publisher,
        createTime: props.values.createTime,
        content: props.values.content
      }
    };
  }

  renderContent = (formVals) => {
    return [
      <Descriptions key='content' column={1} title={formVals.title}>
        <Descriptions.Item>{formatMessage({ id: 'app.notification.publisher' })}:{formVals.publisher} {formatMessage({ id: 'app.notification.create-time' })}:{moment(formVals.createTime).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
        <Descriptions.Item><div dangerouslySetInnerHTML={{ __html: formVals.content }} ></div></Descriptions.Item>
      </Descriptions>
    ];
  };

  render() {
    const { viewModalVisible, handleViewModalVisible, values } = this.props;
    const { formVals } = this.state;
    const okViewHandle = () => {
      const { form, handleView } = this.props;
      const { formVals: oldValue } = this.state;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...oldValue, ...fieldsValue };
        this.setState(
          {
            formVals
          },
          () => {
            handleView(formVals);
          }
        );
      });
    };

    return (
      <Modal
        destroyOnClose
        visible={viewModalVisible}
        onOk={okViewHandle}
        onCancel={() => handleViewModalVisible(false, values)}
        afterClose={() => handleViewModalVisible()}
        width='60%'
        footer={null}
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ myNotification, loading }) => ({
  myNotification,
  loading: loading.models.myNotification
}))
@Form.create()
class MyNotification extends PureComponent {
  state = {
    viewModalVisible: false,
    formValues: {},
    viewFormValues: {},
    typeData: {},
    hiddenMenuButton: localStorage.getItem('mscode_menubutton')
  };

  columns = [
    {
      title: formatMessage({ id: 'app.notification.title' }),
      copyable: true,
      ellipsis: true,
      dataIndex: 'title'
    },
    {
      title: formatMessage({ id: 'app.notification.type' }),
      dataIndex: 'typeCn'
    },
    {
      title: formatMessage({ id: 'app.notification.priority' }),
      dataIndex: 'priorityCn'
    },
    {
      title: formatMessage({ id: 'app.notification.publisher' }),
      dataIndex: 'publisher'
    },
    {
      title: formatMessage({ id: 'app.notification.create-time' }),
      dataIndex: 'createTime',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      render: (text, record) => (
        <Fragment>
          {this.state.hiddenMenuButton.indexOf('mynotification:view') !== -1 ? null :
            <a onClick={() => this.handleViewModalVisible(true, record)}><Icon type="check-circle" />{formatMessage({ id: 'app.common.view' })}</a>
          }
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'myNotification/fetch'
    });
    dispatch({
      type: 'myNotification/fetchType'
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'myNotification/fetch',
      payload: params
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {}
    });
    dispatch({
      type: 'myNotification/fetch'
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      this.setState({
        formValues: values
      });
      dispatch({
        type: 'myNotification/fetch',
        payload: values
      });
    });
  };

  handleViewModalVisible = (flag, record) => {
    this.setState({
      viewModalVisible: !!flag,
      viewFormValues: record || {}
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator }, myNotification: { typeSelectData } } = this.props;
    let typeData;
    if ({ typeSelectData }.typeSelectData) {
      typeData = { typeSelectData }.typeSelectData;
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.notification.title' })}>
              {getFieldDecorator('title')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.notification.content' })}>
              {getFieldDecorator('content')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.notification.type' })}>
              {getFieldDecorator('type')(
                <Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
                  {typeData && typeData.map(d => (
                    <Option key={d.value}>{d.name}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} type="primary" icon="reload">
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { myNotification: { data }, loading } = this.props;
    const { viewModalVisible, viewFormValues } = this.state;
    const viewMethods = {
      handleViewModalVisible: this.handleViewModalVisible,
      handleView: this.handleView
    };
    return (
      <PageHeaderWrapper content={formatMessage({ id: 'app.notification.mynotification' })}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <ProTable
              bordered={true}
              search={false}
              rowKey={record => record.id}
              tableStyle={{ paddingTop: '15px' }}
              loading={loading}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columns={this.columns}
              onChange={this.handleBasicTableChange}
              options={{
                density: true,
                reload: () => {
                  this.handleSearch();
                },
                fullScreen: true,
                setting: true,
              }}
            />
          </div>
        </Card>
        {viewFormValues && Object.keys(viewFormValues).length ? (
          <ViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default MyNotification;